<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\UserAddress;
use think\Validate;

/**
 * 地址管理接口
 */
class Address extends Api
{
    // 无需登录的接口
    protected $noNeedLogin = [];
    // 无需鉴权的接口
    protected $noNeedRight = ['*'];
    
    /**
     * 获取地址列表
     *
     * @ApiMethod (GET)
     */
    public function index()
    {
        $user_id = $this->auth->id;
        $list = UserAddress::where('user_id', $user_id)
            ->order('is_default', 'desc')
            ->order('id', 'desc')
            ->select();
            
        $this->success('获取地址列表成功', ['list' => $list]);
    }
    
    /**
     * 获取地址详情
     *
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, description="地址ID")
     */
    public function detail()
    {
        $id = $this->request->param('id/d');
        if (!$id) {
            $this->error('参数错误');
        }
        
        $user_id = $this->auth->id;
        $address = UserAddress::where('id', $id)
            ->where('user_id', $user_id)
            ->find();
            
        if (!$address) {
            $this->error('地址不存在');
        }
        
        $this->success('获取地址详情成功', ['address' => $address]);
    }
    
    /**
     * 添加地址
     *
     * @ApiMethod (POST)
     * @ApiParams (name="name", type="string", required=true, description="收货人姓名")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="province", type="string", required=true, description="省份")
     * @ApiParams (name="city", type="string", required=true, description="城市")
     * @ApiParams (name="district", type="string", required=true, description="区县")
     * @ApiParams (name="address", type="string", required=true, description="详细地址")
     * @ApiParams (name="zip", type="string", required=false, description="邮编")
     * @ApiParams (name="is_default", type="integer", required=false, description="是否默认 0=否 1=是")
     */
    public function add()
    {
        $params = $this->request->post();
        
        $validate = new Validate([
            'name' => 'require|max:50',
            'mobile' => 'require|regex:/^1\d{10}$/',
            'province' => 'require|max:100',
            'city' => 'require|max:100',
            'district' => 'require|max:100',
            'address' => 'require|max:255',
            'zip' => 'max:10',
            'is_default' => 'in:0,1',
        ], [
            'name.require' => '收货人姓名不能为空',
            'name.max' => '收货人姓名最多50个字符',
            'mobile.require' => '手机号不能为空',
            'mobile.regex' => '手机号格式不正确',
            'province.require' => '省份不能为空',
            'province.max' => '省份最多100个字符',
            'city.require' => '城市不能为空',
            'city.max' => '城市最多100个字符',
            'district.require' => '区县不能为空',
            'district.max' => '区县最多100个字符',
            'address.require' => '详细地址不能为空',
            'address.max' => '详细地址最多255个字符',
            'zip.max' => '邮编最多10个字符',
            'is_default.in' => '是否默认参数错误',
        ]);
        
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        
        $user_id = $this->auth->id;
        
        $address = new UserAddress();
        $address->user_id = $user_id;
        $address->name = $params['name'];
        $address->mobile = $params['mobile'];
        $address->province = $params['province'];
        $address->city = $params['city'];
        $address->district = $params['district'];
        $address->address = $params['address'];
        $address->zip = isset($params['zip']) ? $params['zip'] : '';
        $address->is_default = isset($params['is_default']) ? intval($params['is_default']) : 0;
        
        // 如果设为默认地址，先将其他地址设为非默认
        if ($address->is_default) {
            UserAddress::where('user_id', $user_id)->update(['is_default' => 0]);
        }
        
        if ($address->save()) {
            $this->success('添加地址成功', ['address' => $address]);
        } else {
            $this->error('添加地址失败');
        }
    }
    
    /**
     * 修改地址
     *
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, description="地址ID")
     * @ApiParams (name="name", type="string", required=false, description="收货人姓名")
     * @ApiParams (name="mobile", type="string", required=false, description="手机号")
     * @ApiParams (name="province", type="string", required=false, description="省份")
     * @ApiParams (name="city", type="string", required=false, description="城市")
     * @ApiParams (name="district", type="string", required=false, description="区县")
     * @ApiParams (name="address", type="string", required=false, description="详细地址")
     * @ApiParams (name="zip", type="string", required=false, description="邮编")
     * @ApiParams (name="is_default", type="integer", required=false, description="是否默认 0=否 1=是")
     */
    public function edit()
    {
        $params = $this->request->post();
        
        $validate = new Validate([
            'id' => 'require|integer|gt:0',
            'name' => 'max:50',
            'mobile' => 'regex:/^1\d{10}$/',
            'province' => 'max:100',
            'city' => 'max:100',
            'district' => 'max:100',
            'address' => 'max:255',
            'zip' => 'max:10',
            'is_default' => 'in:0,1',
        ], [
            'id.require' => '地址ID不能为空',
            'id.integer' => '地址ID必须是整数',
            'id.gt' => '地址ID必须大于0',
            'name.max' => '收货人姓名最多50个字符',
            'mobile.regex' => '手机号格式不正确',
            'province.max' => '省份最多100个字符',
            'city.max' => '城市最多100个字符',
            'district.max' => '区县最多100个字符',
            'address.max' => '详细地址最多255个字符',
            'zip.max' => '邮编最多10个字符',
            'is_default.in' => '是否默认参数错误',
        ]);
        
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        
        $user_id = $this->auth->id;
        $address = UserAddress::where('id', $params['id'])
            ->where('user_id', $user_id)
            ->find();
            
        if (!$address) {
            $this->error('地址不存在');
        }
        
        // 只更新提交的字段
        $allowFields = ['name', 'mobile', 'province', 'city', 'district', 'address', 'zip', 'is_default'];
        foreach ($allowFields as $field) {
            if (isset($params[$field])) {
                $address->$field = $params[$field];
            }
        }
        
        // 如果设为默认地址，先将其他地址设为非默认
        if (isset($params['is_default']) && $params['is_default'] == 1) {
            UserAddress::where('user_id', $user_id)
                ->where('id', '<>', $params['id'])
                ->update(['is_default' => 0]);
        }
        
        if ($address->save()) {
            $this->success('修改地址成功', ['address' => $address]);
        } else {
            $this->error('修改地址失败');
        }
    }
    
    /**
     * 删除地址
     *
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, description="地址ID")
     */
    public function delete()
    {
        $id = $this->request->post('id/d');
        if (!$id) {
            $this->error('参数错误');
        }
        
        $user_id = $this->auth->id;
        $address = UserAddress::where('id', $id)
            ->where('user_id', $user_id)
            ->find();
            
        if (!$address) {
            $this->error('地址不存在');
        }
        
        if ($address->delete()) {
            $this->success('删除地址成功');
        } else {
            $this->error('删除地址失败');
        }
    }
    
    /**
     * 设置默认地址
     *
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, description="地址ID")
     */
    public function setDefault()
    {
        $id = $this->request->post('id/d');
        if (!$id) {
            $this->error('参数错误');
        }
        
        $user_id = $this->auth->id;
        $address = UserAddress::where('id', $id)
            ->where('user_id', $user_id)
            ->find();
            
        if (!$address) {
            $this->error('地址不存在');
        }
        
        if (UserAddress::setDefault($user_id, $id)) {
            $this->success('设置默认地址成功');
        } else {
            $this->error('设置默认地址失败');
        }
    }
}